
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;

        // 循环直到输入有效编号
        do {
            System.out.println("1.矩形 2.正方形 3.圆形 4.三角形");
            System.out.print("请选择需要计算面积的图形：");
            while (!scanner.hasNextInt()) {
                System.out.print("输入无效，请重新输入：");
                scanner.next();
            }
            choice = scanner.nextInt();

            if (choice < 1 || choice > 4) {
                System.out.println("输入错误，请重新选择！");
            }
        } while (choice < 1 || choice > 4);

        double area = 0;
        switch (choice) {
            case 1:
                area = getRectangleArea(scanner);
                break;
            case 2:
                area = getSquareArea(scanner);
                break;
            case 3:
                area = getCircleArea(scanner);
                break;
            case 4:
                area = getTriangleArea(scanner);
                break;
        }

        System.out.printf("该图形的面积为：%.2f%n", area);
        scanner.close();
    }

    // 矩形面积
    private static double getRectangleArea(Scanner scanner) {
        double length = getPositiveNumber(scanner, "请输入矩形的长：");
        double width = getPositiveNumber(scanner, "请输入矩形的宽：");
        return length * width;
    }

    // 正方形面积
    private static double getSquareArea(Scanner scanner) {
        double side = getPositiveNumber(scanner, "请输入正方形的边长：");
        return side * side;
    }

    // 圆形面积
    private static double getCircleArea(Scanner scanner) {
        double diameter = getPositiveNumber(scanner, "请输入圆的直径：");
        double radius = diameter / 2;
        return Math.PI * radius * radius;
    }

    // 三角形面积
    private static double getTriangleArea(Scanner scanner) {
        double base = getPositiveNumber(scanner, "请输入三角形的底：");
        double height = getPositiveNumber(scanner, "请输入三角形的高：");
        return 0.5 * base * height;
    }

    // 输入正数验证
    private static double getPositiveNumber(Scanner scanner, String prompt) {
        double number;
        do {
            System.out.print(prompt);
            while (!scanner.hasNextDouble()) {
                System.out.print("输入无效，请重新输入：");
                scanner.next();
            }
            number = scanner.nextDouble();
            if (number <= 0) {
                System.out.println("边长/直径/底/高必须为正数！");
            }
        } while (number <= 0);
        return number;
    }
}
